package essay

import (
	"database/sql"
	"log"

	"gitee.com/taadis/nook/store/model"
	_ "github.com/go-sql-driver/mysql"
)

var (
	driverName     string = "mysql"
	dataSourceName string = "root:root..@/nook?charset=utf8"
)

// 最近随笔
func Recent() (essays []model.Essay, err error) {
	db, err := sql.Open(driverName, dataSourceName)
	if err != nil {
		log.Println(err.Error())
		return nil, err
	}
	defer db.Close()

	query := "select id, title from essay"
	rows, err := db.Query(query)
	if err != nil {
		log.Println(err.Error())
		return nil, err
	}
	defer rows.Close()

	for rows.Next() {
		essay := model.Essay{}
		err = rows.Scan(&essay.Id, &essay.Title)
		if err != nil {
			log.Println(err)
			return nil, err
		}
		essays = append(essays, essay)
	}
	return essays, nil
}

func Add(id string, title string, content string) error {
	//return errors.New("[TODO]随笔存储开发中...")
	db, err := sql.Open(driverName, dataSourceName)
	if err != nil {
		log.Println(err.Error())
		return err
	}
	defer db.Close()

	query := "insert into essay(id, title, content) values(?, ?, ?)"
	_, err = db.Exec(query, id, title, content)
	if err != nil {
		log.Println(err.Error())
	}
	return err
}

// 修改随笔
func Update(id string, title string, content string) error {
	db, err := sql.Open(driverName, dataSourceName)
	if err != nil {
		log.Println(err.Error())
		return err
	}
	defer db.Close()

	query := "update essay set title = ?, content = ? where id = ?"
	_, err = db.Exec(query, title, content, id)
	if err != nil {
		log.Println(err.Error())
	}
	return err
}

// 获取指定id的随笔
func Single(id string) (essay model.Essay, err error) {
	db, err := sql.Open(driverName, dataSourceName)
	if err != nil {
		log.Println(err.Error())
		return
	}
	defer db.Close()

	query := "select id, title, content from essay where id = ?"
	row := db.QueryRow(query, id)
	err = row.Scan(&essay.Id, &essay.Title, &essay.Content)
	if err != nil {
		log.Println(err)
		return
	}
	return
}

// 删除指定的随笔
func Remove(id string) (err error) {
	db, err := sql.Open(driverName, dataSourceName)
	if err != nil {
		log.Println(err)
		return
	}
	defer db.Close()

	query := "delete from essay where id = ?"
	_, err = db.Exec(query, id)
	if err != nil {
		log.Println(err)
		return
	}
	return
}
